package com.sea.base.utils

import android.app.Application
import androidx.annotation.StyleRes
import androidx.appcompat.app.ApplicationInflaterHelper
import com.sea.base.ext.global.throwIf

/**
 * Author: Wu Chang
 * 缓存全局的Context提供给各模块需要的方法使用
 * Date: 2023/3/27 9:56
 */
class AppUtil(
    /**
     * 从Application初始化全局引用的参数
     */
    val context: Application,
    /**
     * 是不是debug
     */
    @JvmField
    val isDebug: Boolean,
    @JvmField
    val buildType: String,
    @JvmField
    val buildTime: Long,
    /**
     * 由宿主Activity主动设置
     */
    @JvmField
    val homeActivityPackageName: String,
    private val defThemeStyleId: Int
) {

    val homeActivitySimpleName = homeActivityPackageName.split(".").last()

    companion object {
        private var _ins: AppUtil? = null

        private var isInstallTheme = false

        @JvmStatic
        val instance: AppUtil
            get() {
                if (!isInstallTheme) {
                    isInstallTheme = true
                    //更新application的主题样式，由于不能在Application构造里执行，所以放在了第一次调用单例的地方
                    _ins?.let {
                        ApplicationInflaterHelper.installFactory(it.defThemeStyleId)
                    }
                }
                return _ins ?: throw IllegalStateException("未初始化过，请在宿主app先调用setInstance")
            }

        /**
         * 仅在宿主app的application的构造中初始化一次
         *
         * @param homeActivityPackageName 首页Activity名称
         * @param defThemeStyleId application配置的主题资源id，用于让application的context支持androidx相关主题
         */
        @JvmStatic
        @Synchronized
        fun setInstance(
            app: Application,
            isDebug: Boolean,
            buildType: String,
            buildTime: Long,
            homeActivityPackageName: String,
            @StyleRes defThemeStyleId: Int,
        ) {
            "该utils已经被初始化过了".throwIf { this._ins != null }
            _ins = AppUtil(app, isDebug, buildType, buildTime, homeActivityPackageName, defThemeStyleId)
        }
    }
}